// 续租
import React, { useState } from 'react'
import {
	Form,
	Row,
	Col,
	Input,
	Space,
	Button,
	Radio,
	Upload,
	message,
	Table,
} from 'antd'
import { ExclamationCircleFilled } from '@ant-design/icons'
import { connect, history, useModel } from 'umi'
import moment from 'moment'
import AdvancedModal from '@/components/Modal/AdvancedModal'
import SelectOrder from '../common/selectOrder'
import SelectScheme from '../common/selectScheme'
import cardStyles from '../index.less'
import { orderRelet, getOrderDetails } from '@/service/order'
import { uploadFileUrl } from '@/service/common/upload'

const formLayout = {
	labelCol: {
		xs: { span: 24 },
		sm: { span: 4 },
	},
	wrapperCol: {
		xs: { span: 24, offset: 0 },
		sm: { span: 12, offset: 0 },
	},
}
function RenewalOrder({ global: { currentRoute }, dispatch }: any) {
	const [form] = Form.useForm()
	const { initialState } = useModel('@@initialState')
	const { fileName } = initialState || {}
	const [openModal, setOpenModal] = useState(false) // 选择订单
	const [oldlist, setOldList] = useState<any[]>([]) // 原方案列表
	const [confirmScheme, setConfirmScheme] = useState(false) // 确认方案
	const [selectScheme, setSelectScheme] = useState(false) // 选择方案
	const [selectSchemeValue, setSelectSchemeInfo] = useState<any[]>([]) // 方案回显列表
	const [programme, setProgramme] = useState('1') // 是否使用之前方案
	const [oldFileList, setOldFileList] = useState<any>([]) // 原车上传验车清单
	const [mortgageAmount, setMortgageAmount] = useState<any>() // 押金
	const [radioState, setRadioState] = useState(true) // 商品方案单选按钮状态
	const [companyIds, setCompanyIds] = useState() // 公司ID
	// 文件上传
	const uploadPropsOld = {
		action: uploadFileUrl,
		name: fileName, // 滴滴上传:file 测试上传:files
		data: {
			modelName: 'renewalOrder',
			targetAttr: 1,
		},
		beforeUpload: (file: any) => {
			const isLt200M = file.size / 1024 / 1024 < 200
			if (!isLt200M) {
				message.error('文件必须小于200MB')
			}
			return isLt200M
		},
		onChange(info: any) {
			if (info.file.status === 'done') {
				setOldFileList(info?.fileList)
				const list: any = []
				info?.fileList?.map((res: any) =>
					list.push(res?.response?.data?.id?.toString()),
				)
				form.setFieldsValue({ attachmentList: list })
			}
			setOldFileList(info?.fileList)
		},
		onRemove(info: any) {
			form.setFieldValue('attachmentList', '')
			message.success(`${info?.name}移除成功`)
		},
		oldFileList,
	}

	// 取消并且关闭当前页面，返回上一个页面
	const onCancel = () => {
		dispatch({
			type: 'global/deleteTabs',
			payload: currentRoute,
		})
		history.goBack()
	}
	// 选择是否延用之前商品方案
	const onChangeScheme = ({ target: { value } }: any) => {
		form.setFieldValue('endTime', '')
		if (value === '0') {
			setConfirmScheme(true)
			const start = form.getFieldValue('startTime')
			const end = form.getFieldValue('end')
			const date = Number(end)
			if (start) {
				const last = moment(new Date(start))
					.subtract(-date, 'months')
					.format('YYYY-MM-DD')
				const dates = moment(new Date(last))
					.subtract(1, 'days')
					.format('YYYY-MM-DD')
				form.setFieldValue('endTime', dates)
			}
		}
		setSelectSchemeInfo([])
		setProgramme(value)
	}
	console.log(programme, 'programme----')
	const columns = [
		// {
		//   title: '商品方案ID',
		//   dataIndex: 'commodityNo',
		// },
		{
			title: '商品方案名称',
			dataIndex: 'commodityName',
			width: 200,
		},
		{
			title: '主体',
			dataIndex: 'subjectName',
			width: 100,
		},
		{
			title: '公司',
			dataIndex: 'affiliatedCompany',
			width: 100,
		},
		{
			title: '城市',
			dataIndex: 'cityName',
			width: 100,
		},
		{
			title: '开始时间',
			dataIndex: 'beginTime',
			width: 150,
			render: (text: any) => <span>{text?.split(' ')[0]}</span>,
		},
		{
			title: '结束时间',
			dataIndex: 'endTime',
			width: 150,
			render: (text: any) => <span>{text?.split(' ')[0]}</span>,
		},
		{
			title: '品牌/车型/车系',
			dataIndex: programme === '1' ? 'brandInfo' : 'applicableGoods',
			width: 200,
		},
		{
			title: '星级',
			dataIndex: 'carStar',
			width: 100,
		},
		{
			title: '订单类型',
			dataIndex: 'rentTypeName',
			width: 150,
		},
		{
			title: '租期',
			dataIndex: 'leaseTerm',
			width: 150,
			render: (text: any) => (
				<>{text > 0 ? <span>{text}</span> : <span>--</span>}</>
			),
		},
		{
			title: '押金',
			dataIndex: 'mortgageAmount',
			width: 150,
			render: (text: any) => <>{text === -1 ? '--' : text}</>,
		},
		{
			title: '定金',
			dataIndex: 'depositAmount',
			width: 150,
			render: (text: any) => <>{text === -1 ? '--' : text}</>,
		},
		{
			title: '月租金(新签)',
			dataIndex: 'rentAmount',
			width: 150,
			render: (text: any) => <>{text === -1 ? '--' : text}</>,
		},
		{
			title: '月租金(续签)',
			dataIndex: 'renewRentAmount',
			width: 150,
			render: (text: any) => <>{text === -1 ? '--' : text}</>,
		},
		{
			title: '首付款',
			dataIndex: 'advancePaymentAmount',
			width: 150,
			render: (text: any) => <>{text === -1 ? '--' : text}</>,
		},
		{
			title: '尾款',
			dataIndex: 'balancePaymentAmount',
			width: 150,
			render: (text: any) => <>{text === -1 ? '--' : text}</>,
		},
		{
			title: '方案状态',
			dataIndex: 'schemeStatus',
			width: 150,
			render: () => <span>有效</span>,
		},
		{
			title: '审核状态',
			dataIndex: 'auditStatus',
			width: 150,
			render: () => <span>审核通过</span>,
		},
	]
	// 提交

	const onFinish = async () => {
		try {
			const values = await form.validateFields()
			const info = {
				quondamOrderCarId: values?.id,
				applyRemark: values?.applyRemark,
				planAdjust: Number(programme),
				plan: {
					planId:
						selectSchemeValue[0]?.id ||
						selectSchemeValue[0]?.planId,
					planNo:
						selectSchemeValue[0]?.commodityNo ||
						selectSchemeValue[0]?.planNo,
					planName:
						selectSchemeValue[0]?.commodityName ||
						selectSchemeValue[0]?.planName,
					rentType:
						selectSchemeValue[0]?.rentTypeId ||
						selectSchemeValue[0]?.rentType,
					rentTypename:
						selectSchemeValue[0]?.rentTypename ||
						selectSchemeValue[0]?.rentTypeName,
					applicableGoods:
						selectSchemeValue[0]?.brandInfo ||
						selectSchemeValue[0]?.applicableGoods,
					tenancy:
						selectSchemeValue[0]?.leaseTerm ||
						selectSchemeValue[0]?.leaseTerm,
					subjectId: selectSchemeValue[0]?.subjectId, // 主体ID
					subjectName: selectSchemeValue[0]?.subjectName, // 主体名称
					affiliatedCompanyId:
						selectSchemeValue[0]?.affiliatedCompanyId, // 公司ID
					affiliatedCompany: selectSchemeValue[0]?.affiliatedCompany, // 公司名称
					cityId: selectSchemeValue[0]?.cityId, // 城市ID
					cityName: selectSchemeValue[0]?.cityName, // 城市名称
					beginTime: selectSchemeValue[0]?.beginTime, // 开始时间
					endTime: selectSchemeValue[0]?.endTime, // 结束时间
					carStar: selectSchemeValue[0]?.carStar, // 星级
					carStarId: selectSchemeValue[0]?.carStarId, // 星级
					modelName: selectSchemeValue[0]?.modelName, // 星级
					planFeeList: [
						{
							feeItemCode: '1',
							feeItemName: '定金',
							feeItemAmount:
								selectSchemeValue[0]?.depositAmount === -1
									? 0
									: selectSchemeValue[0]?.depositAmount ||
									null,
						},
						{
							feeItemCode: '2',
							feeItemName: '押金',
							feeItemAmount:
								selectSchemeValue[0]?.mortgageAmount === -1
									? 0
									: selectSchemeValue[0]?.mortgageAmount ||
									null,
						},
						{
							feeItemCode: '3',
							feeItemName: '月租金(新签)',
							feeItemAmount:
								selectSchemeValue[0]?.rentAmount === -1
									? 0
									: selectSchemeValue[0]?.rentAmount || null,
						},
						{
							feeItemCode: '4',
							feeItemName: '月租金(续签)',
							feeItemAmount:
								selectSchemeValue[0]?.renewRentAmount === -1
									? 0
									: selectSchemeValue[0]?.renewRentAmount ||
									null,
						},
						{
							feeItemCode: '5',
							feeItemName: '首付款',
							feeItemAmount:
								selectSchemeValue[0]?.advancePaymentAmount ===
									-1
									? 0
									: selectSchemeValue[0]
										?.advancePaymentAmount || null,
						},
						{
							feeItemCode: '6',
							feeItemName: '尾款',
							feeItemAmount:
								selectSchemeValue[0]?.balancePaymentAmount ===
									-1
									? 0
									: selectSchemeValue[0]
										?.balancePaymentAmount || null,
						},
					],
				},
				attachmentList: values?.attachmentList,
			}
			if (info?.plan?.planId > 0) {
				const list: any[] = []
				info?.plan?.planFeeList?.forEach((res: any) => {
					if (res?.feeItemAmount) {
						list.push(res)
					}
				})
				info.plan.planFeeList = list
				orderRelet(info).then((res) => {
					if (res.success) {
						onCancel()
					}
				})
			} else {
				message.error('请选择商品方案')
			}
		} catch (errorInfo) {
			/* empty */
		}
	}
	// 选择商品方案
	const selectSchemeInfo = (value: any) => {
		if (Number(value?.mortgageAmount) >= Number(mortgageAmount)) {
			const list = []
			list.push(value)
			setSelectSchemeInfo(list)
			const start = form.getFieldValue('startTime')
			const date = Number(value?.leaseTerm)
			if (start) {
				const last = moment(new Date(start))
					.subtract(-date, 'months')
					.format('YYYY-MM-DD')
				const dates = moment(new Date(last))
					.subtract(1, 'days')
					.format('YYYY-MM-DD')
				form.setFieldValue('endTime', dates)
			}
		} else {
			message.warning('请选择大于等于原方案的押金的方案')
		}
	}
	// 选择订单
	const changeOrder = (datas: any) => {
		setProgramme('1')
		setSelectSchemeInfo([])
		form.setFieldValue('endTime', '')
		form.setFieldValue('planAdjust', '1')
		setRadioState(false)
		const data = datas[0]
		setCompanyIds(data?.lessorId)
		form.setFieldValue('quondamOrderCarId', data?.orderCarNo)
		form.setFieldValue('id', data?.id)
		const start = moment(new Date(data?.reletFinishTime))
			.subtract(-1, 'days')
			.format('YYYY-MM-DD')
		form.setFieldValue('startTime', start)
		getOrderDetails(data?.id).then((res: any) => {
			if (res.success) {
				const value = res?.data?.plan
				const obj = {
					planId: value?.planId,
					commodityNo: value?.planNo,
					commodityName: value?.planName,
					rentType: value?.rentType,
					planTypename: value?.planTypename,
					rentTypeName: value?.rentTypename,
					leaseTerm: value?.tenancy,
					applicableGoods: value?.applicableGoods,
					subjectId: value?.subjectId, // 主体ID
					subjectName: value?.subjectName, // 主体名称
					affiliatedCompanyId: value?.affiliatedCompanyId, // 公司ID
					affiliatedCompany: value?.affiliatedCompany, // 公司名称
					cityId: value?.cityId, // 城市ID
					cityName: value?.cityName, // 城市名称
					beginTime: value?.beginTime, // 开始时间
					endTime: value?.endTime, // 结束时间
					carStar: value?.carStar, // 星级
					carStarId: value?.carStarId, // 星级ID
					modelName: value?.modelName, // 车系车型id
					mortgageAmount: '',
					rentAmount: '',
					renewRentAmount: '',
					advancePaymentAmount: '',
					balancePaymentAmount: '',
					depositAmount: '',
				}
				form.setFieldValue('end', value?.tenancy) // 给租赁结束日赋值
				res?.data?.plan?.planFeeList?.forEach((res1: any) => {
					if (res1.feeItemCode === '1') {
						obj.depositAmount = res1.feeItemAmount
					}
					if (res1.feeItemCode === '2') {
						obj.mortgageAmount = res1.feeItemAmount
						setMortgageAmount(res1.feeItemAmount) // 押金
					}
					if (res1.feeItemCode === '3') {
						obj.rentAmount = res1.feeItemAmount
					}
					if (res1.feeItemCode === '4') {
						obj.renewRentAmount = res1.feeItemAmount
					}
					if (res1.feeItemCode === '5') {
						obj.advancePaymentAmount = res1.feeItemAmount
					}
					if (res1.feeItemCode === '6') {
						obj.balancePaymentAmount = res1.feeItemAmount
					}
				})
				const list = []
				list.push(obj)
				setOldList(list)
			}
		})
	}
	return (
		<div className={cardStyles.page}>
			<div className={cardStyles.card}>
				<p className={cardStyles.title}>续租信息</p>
				<div>
					<Form
						name="basic"
						form={form}
						onFinish={onFinish}
						onFinishFailed={() => { }}
						autoComplete="off"
						{...formLayout}
						wrapperCol={{ flex: 1 }}>
						<Row gutter={24} className={cardStyles.rows}>
							<Col span={24}>
								<Form.Item
									name="quondamOrderCarId"
									label="选择续租订单"
									rules={[
										{
											required: true,
											message: '请选择续租订单',
										},
									]}>
									<Input
										placeholder="选择续租订单"
										style={{ width: '300px' }}
										onClick={() => {
											setOpenModal(true)
											setProgramme('1')
										}}
									/>
								</Form.Item>
							</Col>
							<Col span={0}>
								<Form.Item name="id" />
							</Col>
						</Row>
						<Row gutter={24} className={cardStyles.rows}>
							<Col span={24}>
								<Form.Item
									name="planAdjust"
									label="商品方案"
									rules={[
										{
											required: true,
											message: '请选择续租商品方案',
										},
									]}>
									<Radio.Group
										onChange={onChangeScheme}
										value={programme}>
										<Radio value="1" disabled={radioState}>
											选择新续租方案
											<Input
												placeholder="请选择续租商品方案"
												style={{
													width: '150px',
													marginLeft: '10px',
												}}
												onClick={() => {
													if (
														form.getFieldValue(
															'quondamOrderCarId',
														)
													) {
														setSelectScheme(true)
													} else {
														message.warning(
															'请先选择续租订单',
														)
													}
												}}
											/>
										</Radio>
										<Radio value="0" disabled={radioState}>
											保持原商品方案
										</Radio>
									</Radio.Group>
								</Form.Item>
							</Col>
							{/* 默认是隐藏商品方案表格的，选择续租订单后，带出订单原有的商品方案或者重新选择商品方案 */}
							<Col span={24}>
								<Table
									key="id"
									columns={columns}
									dataSource={selectSchemeValue}
									style={{ width: '80%', margin: '0 auto' }}
									bordered
									scroll={{ x: 1000, y: 400 }}
									pagination={false}
								/>
							</Col>
						</Row>
						<Row gutter={24} className={cardStyles.rows}>
							<Col span={24}>
								{/* 选择订单后，带出起始时间 */}
								<Form.Item label="租赁开始日" name="startTime">
									<Input disabled />
								</Form.Item>
								<Form.Item label="租赁结束日" name="endTime">
									<Input disabled />
								</Form.Item>
							</Col>
							<Col span={0}>
								<Form.Item name="end" />
							</Col>
						</Row>
						<Row gutter={24} className={cardStyles.rows}>
							<Col span={24}>
								<Form.Item name="applyRemark" label="续租备注">
									<Input
										maxLength={200}
										placeholder="请输入续租备注，不超过200个字符"
										allowClear
										style={{ width: '600px' }}
									/>
								</Form.Item>
							</Col>
						</Row>
						<Row gutter={24} className={cardStyles.rows}>
							<Col span={24}>
								<Form.Item
									label="续租附件"
									name="attachmentList">
									<Upload {...uploadPropsOld}>
										{oldFileList?.length >= 5 ? null : (
											<Button>添加附件</Button>
										)}
									</Upload>
									<p style={{ margin: '15px 0 0 0' }}>
										附件说明：附件最大支持30M，
									</p>
									<p>支持格式：PDF、Word、Excel、JPG、PNG</p>
								</Form.Item>
							</Col>
						</Row>
						<Row justify="center" style={{ marginTop: '20px' }}>
							<Form.Item>
								<Space>
									<Button shape="round" onClick={onCancel}>
										取消
									</Button>
									<Button
										shape="round"
										type="primary"
										htmlType="submit">
										提交
									</Button>
								</Space>
							</Form.Item>
						</Row>
					</Form>
				</div>
				{openModal && (
					<SelectOrder
						title="选择续租订单"
						setIsOpen={setOpenModal}
						isOpen={openModal}
						selectOrder={changeOrder}
						type="renewal"
					/>
				)}
				{companyIds && (
					<SelectScheme
						title="选择方案"
						isOpen={selectScheme}
						setIsOpen={setSelectScheme}
						selectOrder={selectSchemeInfo}
						type="1"
						orgIds={companyIds}
					/>
				)}
				<AdvancedModal
					isOpen={confirmScheme}
					setIsOpen={setConfirmScheme}
					title="商品方案确认"
					onOk={() => {
						setProgramme('1')
						setConfirmScheme(false)
						setSelectSchemeInfo(oldlist)
					}}
					onClose={() => {
						setProgramme('1')
						form.setFieldValue('planAdjust', '1')
					}}
				>
					<p>
						<ExclamationCircleFilled
							style={{ marginRight: '10px', color: '#faad14' }}
						/>
						确认要选择原商品方案吗？
					</p>
				</AdvancedModal>
			</div>
		</div>
	)
}
export default connect(({ global }: any) => ({ global }))(RenewalOrder)
